/**
* @description : 公共文书通用组件
* @descriptionDetail : 文书通用
* @copyright : 浙江烟草
* @author : mc
* @create : 2022-12-05 16:25:33
*/
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="docConfig.docName" :custom-back="goBack" style="z-index: 99999">
			<view class="nav-right-icon">
				<u-icon name="download" v-if="documentDoc.pdfFileId" color="#FFF" @tap="onPrint"></u-icon>
				<u-icon name="eye-fill" style="margin-left: 20rpx;" color="#FFF" @tap="regDetail"></u-icon>
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-DINGDING || H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view class="content u-page" :class="($slots.bizBtns || (documentDoc.step === 'add' || documentDoc.step === 'edit') || (documentDoc.step && documentDoc.step !== 'edit' && documentDoc.step !== 'view')) ? 'content-padding-bottom':''">
			<u-form ref="docFormRef" :model="docFormData" label-position="top" label-width="auto" :error-type="['border-bottom']">
				<slot name="formItems" :formData="docFormData" :justView="justView"></slot>
				<template v-if="hasAttr">
					<u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
					<form-section title="附件信息"></form-section>
					<u-form-item label="">
						<m-upload :maxCount="justView ? 0 : attrMaxCount" :uploadParam="uploadParam" upApiUrl="uploadBase64ForApp" :deletable="!justView" :fileList="fileList" :disabled="justView" index="docCom" :canUploadFun="canUpload" @on-list-change="fileChange"></m-upload>
					</u-form-item>
				</template>
				<template v-if="approve.length > 0 && approveInfoShow">
					<u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
					<form-section title="审批信息" :customStyle="customStyle"></form-section>
					<u-form-item :label="itm.gfaName" v-for="itm in approve" :key="itm.gfaCode">
						<view class="approve-lay">
							<u-input v-model="itm.approveInfo" :disabled="currApprove.gfaCode != itm.gfaCode" type="textarea" :placeholder="currApprove.gfaCode != itm.gfaCode ? '' : '请输入审核意见'"></u-input>
							<view class="approve-lay-bt">
								<view>
									审核人: <text style="margin-left: 10rpx;color: #393B3D;">
										{{ itm.approvePersonName }}
									</text>
								</view>
								<view style="text-align: right;" @click="onDatePick(itm.gfaCode)">
									审核时间: <text style="margin-left: 10rpx;color: #393B3D;">
										{{ itm.approveDate }}
									</text>
								</view>
							</view>
						</view>
					</u-form-item>
				</template>
			</u-form>
		</view>
		<view class="submit-btns btn-other-cls" v-if="$slots.bizBtns || (documentDoc.step === 'add' || documentDoc.step === 'edit') || (documentDoc.step && documentDoc.step !== 'edit' && documentDoc.step !== 'view')">
			<slot name="bizBtns" v-if="$slots.bizBtns"></slot>
			<!--新办 编辑的时候-->
			<template v-else-if="documentDoc.step === 'add' || documentDoc.step === 'edit'">
				<u-button class="u-btn" plain type="primary" @click="save">
					保存
				</u-button>
				<u-button class="u-btn" type="primary" @click="submit">
					提交
				</u-button>
			</template>
			<!--审核审批的时候-->
			<template v-else-if="(documentDoc.step && documentDoc.step !== 'edit' && documentDoc.step !== 'view')">
				<u-button class="u-btn" type="error" v-if="currApprove.gfaCode" @click="disagree">
					退回
				</u-button>
				<u-button class="u-btn" type="primary" @click="agree">
					{{ documentDoc.step === '00' ? "提交" : "审批通过" }}
				</u-button>
			</template>
		</view>

		<u-popup v-model="personChoseVisible" length="80%" mode="bottom">
			<flow-user-select-com :flow-nodes="approve" :biz-uuid="bizUuid" :hasBackIcon="false" :flow-code="docConfig.flowFormCode" @flowUserSelectBack="onPersonChose"></flow-user-select-com>
		</u-popup>
		<!-- 线索详情 -->
		<u-popup v-model="regDetailVisible" length="80%" mode="right">
			<registrationDetails :detailInfo="detailInfo"></registrationDetails>
		</u-popup>
		<u-calendar mode="date" :min-date="minDate" :max-date="maxDate" v-model="calShow" @change="dateConfirm"></u-calendar>
	</view>
</template>

<script>
	/**
	 * slot bizBtns   业务操作btn
	 */
	import FormSection from "@/components/form-section.vue";
	import commonService from "@/service/common/common.service.js";
	import FlowUserSelectCom from "./flowUserSelectCom.vue";
	import MUpload from "@/components/m-upload.vue";
	import registrationDetails from "../intelligence/intelligenceFilesInfo/registrationDetails.vue"
	import inteligenceService from '@/service/intelligence/intelligence.service.js';
	import fabButton from '@/components/uni-fab.vue';
	export default {
		name: "DocComponent",
		components: {
			FormSection,
			FlowUserSelectCom,
			MUpload,
			registrationDetails,
			fabButton
		},
		props: {
			bizUuid: {
				type: String,
				default: "",
			},
			docType: {
				type: String,
				default: "",
			},
			sdocUuid: {
				type: String,
				default: "",
			},
			docCode: {
				type: String,
				default: "",
			},
			docInsUuid: {
				type: String,
				default: "",
			},
			mainInfo: {
				type: Object,
				default: () => {
					return {}
				},
			},
			extraDoc: { // 额外补充的文书信息，数据优先级高于查询到的文书信息，同名字段谨慎使用
				type: Object,
				default: () => {
					return {}
				},
			},
			getBackCode: {
				type: Function,
				default: () => {},
			},
			rules: {
				type: Object,
				default: () => {
					return undefined;
				},
			},
			hasAttr: { // 是否展示附件
				type: Boolean,
				default: true,
			},
			attrMaxCount: { // 附件最大个数
				type: Number,
				default: 999,
			},
			setDefaultVal: {
				type: Function,
				default: function(obj) {},
			},
			detailInfo: { // 查看线索详情数据
				type: Object,
				default: () => {
					return {}
				},
			},
		},
		data() {
			return {
				user: this.$store.state.userInfo,
				docUuid: '',
				docFormData: {},
				docConfig: {},
				documentDoc: {},
				docIns: {},
				docNo: "",
				calShow: false,
				sBizUuid: '',
				approve: [],
				titemUuid: '',
				isQuering: false,
				currApprove: {},
				nextPersonInfo: {},
				optType: "",
				personChoseVisible: false,
				justView: false,
				fileList: [],
				customStyle: {
					"backgroundColor": "#ffffff",
					"marginTop": "10rpx",
					"marginBottom": "10rpx",
				},
				approveInfoShow: true,
				uploadParam: {
					fiGroupCode: this.$FILE_GROUP_TYPE.s_doc_word_instance,
				},
				regDetailVisible: false,
				minDate: "1920-01-01",
				maxDate: this.$u.timeFormat(new Date().getTime(), "yyyy-mm-dd"),
				fContent: [{
						iconPath: require("@/static/down.png"),
						selectedIconPath: require("@/static/down.png"),
						text: '下载',
						active: false,
					},

				],
			}
		},
		watch: {
			documentDoc: {
				immediate: true,
				deep: true,
				handler(val) {
					this.justView = val.step !== 'edit';
					this.approveInfoShow = val.step !== 'add' && val.step !== 'edit';
				},
			},
		},
		created() {
			this.sBizUuid = this.bizUuid;
			this.docUuid = this.sdocUuid;
			this.initData();
		},
		mounted() {
			if (this.rules) {
				this.$refs.docFormRef.setRules(this.rules);
			}
			// this.setRightBtns();
		},
		methods: {
			getPdfFileId() {
				if (this.documentDoc.pdfFileId) {
					this.fContent.push({
						iconPath: require("@/static/oview.png"),
						selectedIconPath: require("@/static/oview.png"),
						text: '预览',
						active: false,
					})
				}
			},
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				this.$deviceApi.setMenu([{
					"id": "1",
					"text": "下载",
				}, {
					"id": "2",
					"text": "查看",
				}, ], (res) => {
					if (res.id == '1') {
						// TODO 刷新
						this.onPrint();
					} else {
						// 弹出more
						this.regDetailVisible = true;
					}
				});
				// #endif
			},
			onDatePick(gfaCode) {
				if (this.currApprove.gfaCode != gfaCode) return;
				this.calShow = true;
			},
			dateConfirm(e) {
				this.currApprove.approveDate = this.$u.timeFormat((new Date(e.result)).getTime(), 'yyyy年mm月dd日');
				for (let i = 0; i < this.approve.length; i++) {
					if (this.currApprove.gfaCode == this.approve[i].gfaCode) {
						this.approve[i].approveDate = this.currApprove.approveDate;
						break;
					}
				}
			},
			regDetail() {
				this.regDetailVisible = true;
			},
			initData() {
				this.getDocInfo();
			},
			getGapMarginRowNumber() {
				return "-" + this.$theme.cm_content_paddng_row.replace('rpx', '');
			},
			setFormDataByKey(key, val) {
				this.$set(this.docFormData, key, val);
			},
			getFileList() {
				if (this.$u.test.isEmpty(this.uploadParam.bizId)) {
					return;
				}
				commonService.goFiles(this.uploadParam.bizId, this.$FILE_GROUP_TYPE.s_doc_word_instance).then(res => {
					if (res.success) {
						this.fileList = [...res.data, ];
					}
				}).catch(e => {
					console.log(e)
				})
			},
			/**
			 * 获取文书的配置信息和文书的抽象信息和具体信息
			 */
			getDocInfo() {
				if (this.bizUuid) {
					this.uploadParam.bizId = this.bizUuid;
					this.initMainInfo();
				}
				this.$modal.showLoading('文书信息加载中...');
				if (this.docInsUuid) {
					this.uploadParam.bizId = this.docInsUuid;
					commonService.getDocIns(this.docInsUuid).then(r => {
						if (r.success) {
							this.documentDoc = r.bean;
							this.docConfig = r.bean.configIns;
							Promise.all([this.getDoc(), this.getFlowNode(), ]).then(() => this.$modal.hideLoading());
							this.getPdfFileId()
						} else {
							this.$modal.hideLoading();
							this.$u.toast(r.msg);
						}
					});
				} else {
					if (this.docUuid) {
						commonService.getById(this.docUuid).then(r => {
							if (r.success) {
								this.docConfig = r.bean;
								this.documentDoc = {
									step: 'edit',
								};
								Promise.all([this.getDoc(), this.getFlowNode(), ]).then(() => this.$modal.hideLoading());
							} else {
								this.$modal.hideLoading();
								this.$u.toast(r.msg);
							}
						});
					} else if (this.docCode) {
						commonService.getDocConfig(this.docCode).then(dr => {
							this.docUuid = dr.bean.docUuid;
							commonService.getById(dr.bean.docUuid).then(r => {
								this.docConfig = r.bean;
								if (r.success) {
									this.docConfig = r.bean;
									this.documentDoc = {
										step: 'edit',
									};
									Promise.all([this.getDoc(), this.getFlowNode(), ]).then(() => this.$modal.hideLoading());
								} else {
									this.$modal.hideLoading();
									this.$u.toast(r.msg);
								}
							});
						});
					}
				}
			},
			initMainInfo(cb) {
				if (this.mainInfo && this.mainInfo.typeCode && !this.titemUuid) {
					let mInfo = this.mainInfo;
					// 初始化主业务流程
					mInfo.bizUuid = this.sBizUuid;
					commonService.initOtherMain(mInfo).then(r => {
						if (r.success) {
							// this.$u.toast('初始化成功');
							console.log('初始化成功');
							this.titemUuid = r.bean.titemUuid;
							cb && cb();
						} else {
							this.$u.toast(r.msg);
						}
					});
				} else {
					cb && cb();
				}
			},
			getDoc() {
				this.getFileList();
				return commonService.getDoc({
					id: this.docInsUuid,
					docUuid: this.docUuid,
					bizUuid: this.bizUuid,
				}, this.docConfig.controllerPath, this.docConfig.docType).then(r => {
					if (r.success) {
						let docData = r.data || [];
						if (JSON.stringify(this.detailInfo) === "{}") {
							// this.detailInfo = r.data[0];
							inteligenceService.getByUuid({
								uuid: r.data[0].clueUuid,
							}).then(res => {
								if (res.success) {
									Object.assign(this.detailInfo, res.bean);
								} else {
									this.$modal.alert(res.msg, () => {
										this.error();
									});
								}
							}).catch(e => {
								this.$modal.alert("请求异常:" + e, () => {
									this.error();
								});
							});
						}
						let docIns = {};
						docData.forEach(d => {
							Object.assign(docIns, d);
						});
						// 补充额外的文书信息
						Object.assign(docIns, this.extraDoc);
						this.docIns = docIns;
						this.docNo = docIns.fullDocNo;
						this.docFormData = this.$u.deepClone(this.docIns);
						if (this.docCode == 'clueReportInfo') { // 是举报记录表则处理
							try {
								this.minDate = this.$u.timeFormat(new Date(this.docFormData.createTime), 'yyyy-mm-dd');
							} catch (e) {
								console.log(e)
							}
						}
						this.docFormData.reportPersonDesc = this.docFormData.reportPersonDesc ? this.docFormData.reportPersonDesc : '保密';
						// this.setDefaultVal(this.docFormData);
					} else {
						this.$modal.hideLoading();
					}
				});
			},
			/**
			 * 获取文书的所有节点
			 */
			getFlowNode() {
				if (this.isQuering) {
					return;
				}
				this.isQuering = true;
				if (!this.docConfig.isHaveFlow) {
					return;
				}
				return commonService.approves({
					docUuid: this.docConfig.docUuid,
					id: this.docInsUuid,
				}).then(r => {
					if (r.success) {
						let nodes = r.data;
						let curStep = this.documentDoc.step;
						console.log(curStep, '------>');
						for (let i = 0; i < nodes.length; i++) {
							let a = nodes[i];
							a.isLast = i === nodes.length - 1;
							if (a.gfaCode === curStep) {
								if (this.docIns.createTime) {
									a.approveDate = this.$u.timeFormat(new Date(this.docIns.createTime).getTime(), 'yyyy年mm月dd日');
								} else {
									a.approveDate = this.$u.timeFormat(Date.now(), 'yyyy年mm月dd日');
								}
								a.approvePersonUuid = this.user.user.personUuid;
								a.approvePersonName = this.user.user.personName;
								a.current = true;
								this.currApprove = a;
							}
						}
						this.approve = nodes;
						if (this.documentDoc.step !== 'view') {
							this.$set(this.approve[0], 'approveInfo', '同意')
						}
					} else {
						this.$modal.hideLoading();
						this.$u.toast(r.msg);
					}
				});
			},
			save(cb, type) {
				if (!this.validateDocNo()) {
					return false;
				}
				this.$refs.docFormRef.validate(vaild => {
					if (!vaild) {
						return;
					}
					this.initMainInfo(() => {
						this.docFormData.fullDocNo = this.docNo;
						console.log(this.docFormData);
						if (!this.docFormData.bizUuid) {
							this.docFormData.bizUuid = this.bizUuid;
							this.docFormData.uuid = this.bizUuid;
						}
						this.$modal.showLoading('文书保存中...');
						commonService.saveDoc(this.docFormData, this.docConfig.controllerPath, {
							titemUuid: this.titemUuid,
							docUuid: this.docUuid,
						}, this.docConfig.docType).then(r => {
							this.$modal.hideLoading();
							if (r.success) {
								this.documentDoc = Object.assign(r.data[0], {
									step: 'edit',
								});
								this.docFormData = r.bean;
								this.docNo = r.bean.fullDocNo;
								this.$u.toast('保存文书成功');
								if (type === 'submit') {
									cb && cb(r.bean, this.docFormData);
								} else {
									this.back();
								}
							} else {
								this.$u.toast(r.msg);
							}
						});
					});
				});
				return false;
			},
			submit() {
				this.$refs.docFormRef.validate(vaild => {
					if (vaild) {
						this.openPersonChose('submit', this.docFormData);
					}
				});
			},
			checkApprove() {
				this.approve.forEach(it => {
					if (it.gfaCode == this.currApprove.gfaCode) {
						this.currApprove.msg = it.approveInfo;
						this.currApprove.date = it.approveDate;
					}
				});
				if (!this.currApprove.msg) {
					this.currApprove.msg = '';
				}
				if (this.$u.test.isEmpty(this.currApprove.msg)) {
					this.$u.toast('请输入审批意见');
					return false;
				}
				if (!this.currApprove.date) {
					this.currApprove.date = this.$u.timeFormat(Date.now(), 'yyyy年mm月dd日');
				}
				return true;
			},
			disagree() {
				if (!this.checkApprove()) {
					return false;
				}
				let stepCode = this.getBackCode();
				stepCode = stepCode || '';
				let approveInfo = this.currApprove;
				let gfaCode = approveInfo.gfaCode;
				let urlParam = {
					approveDate: approveInfo.date,
					approveInfo: approveInfo.msg && approveInfo.msg !== '同意' ? approveInfo.msg : '退回',
					approvePersonUuid: this.user.user.personUuid,
					nextPersons: '',
					gfaCode: gfaCode,
					stepCode: stepCode,
				};
				this.$modal.showLoading('文书退回中...');
				let disagree = commonService.backToFirst;
				if (stepCode) {
					disagree = commonService.disagree;
				}
				disagree(this.docIns, this.docConfig.controllerPath, urlParam, this.docConfig.docType).then(r => {
					this.$modal.hideLoading();
					if (r.success) {
						this.$u.toast('文书退回成功');
						this.back();
					}
				});
			},
			agree() {
				if (!this.checkApprove()) {
					return false;
				}
				this.$refs.docFormRef.validate(vaild => {
					if (vaild) {
						this.openPersonChose('agree', this.docFormData);
					}
				});
			},
			/**
			 * 打开下一步用户选择
			 */
			openPersonChose(optType, formData) {
				this.nextPersonInfo = {};
				if (formData.hidePersonChose) {
					this.nextPersonInfo.nextPersonUuids = formData.nextPersonUuids || "";
				}
				this.optType = optType;
				if (this.docConfig.isHaveFlow && !this.currApprove.isLast) {
					if (formData.hidePersonChose) {
						this.$modal.confirm("流程将提交给【" + formData.nextPersonNames + "】，您确认要提交吗？", () => {
							this.doSubmitOrAgree(formData);
						});
					} else {
						this.personChoseVisible = true;
					}
				} else {
					this.doSubmitOrAgree(formData);
				}
			},
			/**
			 * 提交获取同意等
			 */
			doSubmitOrAgree(formData) {
				let type = this.optType;
				let nextPsrUuids = this.nextPersonInfo.nextPersonUuids;
				if (type === 'submit') {
					this.initMainInfo(() => {
						this.save((saveResult, saveParam) => {
							let urlParam = {
								titemUuid: this.titemUuid,
								docUuid: this.docUuid,
								nextPersons: nextPsrUuids || '',
								belong: this.docType,
							};
							this.$modal.showLoading('提交中...');
							commonService.submit(saveResult, this.docConfig.controllerPath, urlParam, this.docConfig.docType, ).then(r => {
								this.$modal.hideLoading();
								if (r.success) {
									this.$u.toast('文书提交成功');
									this.docDone(formData.nonCloseDoc);
								} else {
									this.$u.toast(r.msg);
								}
							}).catch(res => {
								this.$modal.hideLoading();
								this.$u.toast('文书提交失败');
								console.log(res);
							});
						}, 'submit');
					});
				} else if (type === 'agree') {
					let approveInfo = this.currApprove;
					let urlParam = {
						approveDate: approveInfo.date,
						approveInfo: approveInfo.msg,
						approvePersonUuid: this.user.user.personUuid,
						nextPersons: nextPsrUuids || '',
						gfaCode: approveInfo.gfaCode,
					};
					this.$modal.showLoading('文书审批中...');
					commonService.agree(formData, this.docConfig.controllerPath, urlParam, this.docConfig.docType, ).then(r => {
						this.$modal.hideLoading();
						if (r.success) {
							this.$u.toast('文书审批成功');
							this.docDone(formData.nonCloseDoc);
						} else {
							this.$u.toast(r.msg);
						}
					}).catch(e => {
						this.$modal.hideLoading();
						this.$u.toast('文书审批失败');
						console.log(e);
					});
				}
			},
			docDone(nonCloseDoc) {
				// if(nonCloseDoc){
				//   this.initData();
				// }
				// 是否关闭
				// this.$emit("docDone",nonCloseDoc);
				this.back();
			},
			back() { // 文书操作完了,推出页面
				this.$emit("back", true);
			},
			/**
			 * 下一步用户
			 */
			onPersonChose(nextInfo) {
				this.nextPersonInfo = {
					nextPersonNames: nextInfo.map(itm => {
						return itm.personName;
					}).join(','),
					nextPersonUuids: nextInfo.map(itm => {
						return itm.personId;
					}).join(','),
				};
				this.personChoseVisible = false;
				this.$refs.docFormRef.validate(vaild => {
					this.doSubmitOrAgree(this.docFormData);
				});
			},
			/**
			 * 检验文书编号
			 */
			validateDocNo() {
				if (!this.checkDocNo(this.docNo)) {
					this.$u.toast('请输入文书编号,格式 xx烟xx[xx]号');
					return false;
				}
				return true;
			},
			checkDocNo(docNo) {
				if (!docNo) {
					return true;
				}
				let reg = /[^\﹝\﹞]*﹝(.*)\][^\﹞]*/;
				let docIdx = docNo.replace(reg, '$1');
				return !(!docIdx || !docIdx.trim());
			},
			fileChange(f) {
				console.log(f);
				this.fileList = [...f, ];
			},
			onPrint() {
				this.setRouteParam({
					fileId: this.documentDoc.pdfFileId,
					fileName: this.docConfig.docName,
				});
				// 跳转详情页面
				this.$u.route("/pages/commonPage/printerComponent");
			},
			canUpload(index) {
				if (index == 'docCom') {
					if (this.documentDoc.docInsUuid) return true;
					this.$u.toast('请先保存文书');
					return false;
				}
				return true;
			},
			fabtrigger(act) {
				if (act.index === 0) {
					this.onPrint()
				} else if (act.index === 1) {
					this.regDetail()
				}
			}
		},
	}
</script>

<style scoped lang="scss">
	.page {
		padding: 0;
	}

	.nav-right-icon {
		margin-right: 30rpx;
		font-size: .8rem;
		color: #FFF;
	}

	.content {
		padding: $cm_conent_padding_column $cm_content_paddng_row;
	}

	.content-padding-bottom {
		padding-bottom: 150rpx !important;
	}

	.approve-lay {
		width: 100%;
	}

	.approve-lay-bt {
		width: 100%;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		display: inline-flex;
		flex-direction: row;
		color: $cm-form-item-label-color;
		justify-content: space-between;
		align-items: center;
		font-size: 28rpx;
	}
</style>
